<template>
	<div class="page-container">
		<h1>日期计算器</h1>
		<el-form ref="form" :model="form" label-position="top">
			<el-form-item label="开始日期">
				<el-date-picker v-model="form.startDate" type="date" placeholder="请选择开始日期"></el-date-picker>
			</el-form-item>
			<el-form-item label="结束日期" v-if="calculationType === 'interval'">
				<el-date-picker v-model="form.endDate" type="date" placeholder="请选择结束日期"></el-date-picker>
			</el-form-item>
			<el-form-item label="间隔天数" v-if="calculationType === 'target'">
				<el-input-number v-model.number="form.intervalDays"></el-input-number>
			</el-form-item>
			<el-form-item>
				<el-radio-group v-model="calculationType">
					<el-radio-button :label="'interval'">日期间隔</el-radio-button>
					<el-radio-button :label="'target'">目标日期</el-radio-button>
				</el-radio-group>
				<el-button @click="resetForm" style="margin-left: 1em;">重置</el-button>
			</el-form-item>
			<el-form-item label="计算结果">
				<p class="result-text">{{ calculationResult }}</p>
			</el-form-item>
			<el-form-item>
				
			</el-form-item>
		</el-form>
		
	</div>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					startDate: new Date(),
					endDate: new Date(),
					intervalDays: 0,
				},
				calculationType: 'interval',
			};
		},
		computed: {
			calculationResult() {
				if (this.calculationType === 'interval') {
					const {
						startDate,
						endDate
					} = this.form;
					if (!startDate || !endDate) {
						return '';
					}
					const oneDayInMs = 1000 * 60 * 60 * 24;
					const startDateMs = +new Date(startDate);
					const endDateMs = +new Date(endDate);
					const intervalInMs = endDateMs - startDateMs;
					const intervalInDays = Math.round(intervalInMs / oneDayInMs);
					return `${intervalInDays} 天`;
				} else {
					const {
						startDate,
						intervalDays
					} = this.form;
					if (!startDate || !intervalDays) {
						return '';
					}
					const oneDayInMs = 1000 * 60 * 60 * 24;
					const startDateMs = +new Date(startDate);
					const targetDateMs = startDateMs + intervalDays * oneDayInMs;
					const targetDate = new Date(targetDateMs);
					const targetDateString = targetDate.toLocaleDateString();
					return targetDateString;
				}
			},
		},
		methods: {
			calculateDate() {
				if (this.calculationType === 'interval') {
					const {
						startDate,
						endDate
					} = this.form;
					if (!startDate || !endDate) {
						this.$message.error('请选择开始日期和结束日期');
						return;
					}
				} else {
					const {
						startDate,
						intervalDays
					} = this.form;
					if (!startDate || !intervalDays) {
						this.$message.error('请选择开始日期并输入间隔天数');
						return;
					}
				}
			},
			resetForm() {
				this.form.startDate = new Date();
				this.form.endDate = new Date();
				this.form.intervalDays = 0;
				this.calculationType = 'interval';
			},
		},
	};
</script>

<style>
	.result-text {
		font-size: 24px;
		font-weight: bold;
	}
</style>
